package domain ;

import java.util.Random ;

import junit.framework.TestCase ;
import persistence.Definitions ;
import persistence.PersistenceController ;
import persistence.PersistenceFactory ;
import persistence.hibernate.HibernatePersistenceFactory ;
import persistence.xstream.XStreamPersistenceFactory ;
import persistence.xstream.XmlDatabaseFileList ;

/**
 * @author idan
 */
public abstract class AbstractServerTest extends TestCase
{

	protected static final int SEED_FOR_RANDOM = 2000 ;
	protected final Random randomGenerator ;
	protected PersistenceFactory persistenceGenerator ;

	public AbstractServerTest()
	{
		super() ;
		this.randomGenerator = new Random(AbstractServerTest.SEED_FOR_RANDOM) ;
	}

	protected abstract void clearDatabase() ;

	protected XmlDatabaseFileList getEmptyFileList()
	{
		XmlDatabaseFileList files = new XmlDatabaseFileList() ;
		String path = Definitions.makePath(Definitions.DATA_DIRECTORY, this.getClass()) ;
		files.setDirectoryFile(path + "directoriesEmtpy.xml") ;
		files.setThreadFile(path + "threadsEmtpy.xml") ;
		files.setPostFile(path + "postsEmtpy.xml") ;
		files.setMemberFile(path + "membersEmpty.xml") ;
		files.setLoginFile(path + "loginsEmpty.xml") ;
		return files ;
	}

	protected XmlDatabaseFileList getNonemptyFileList()
	{
		XmlDatabaseFileList files = new XmlDatabaseFileList() ;
		String path = Definitions.makePath(Definitions.DATA_DIRECTORY, this.getClass()) ;
		files.setDirectoryFile(path + "directories.xml") ;
		files.setThreadFile(path + "threads.xml") ;
		files.setPostFile(path + "posts.xml") ;
		files.setMemberFile(path + "members.xml") ;
		files.setLoginFile(path + "logins.xml") ;
		return files ;
	}

	protected PersistenceFactory newHibernatePersistenceGenerator(final boolean load)
	{
		return new HibernatePersistenceFactory(load) ;
	}

	protected PersistenceFactory newPersistenceGenerator(final boolean load, final boolean isEmpty)
	{
		return this.newXStreamPersistenceGenerator(load, isEmpty) ;
		//return this.newHibernatePersistenceGenerator(load) ;
	}

	protected PersistenceFactory newXStreamPersistenceGenerator(final boolean load, final boolean isEmpty)
	{

		if (!isEmpty)
		{
			XmlDatabaseFileList files = this.getNonemptyFileList() ;
			return new XStreamPersistenceFactory(load, files) ;
		}
		else
		{
			XmlDatabaseFileList files = this.getEmptyFileList() ;
			return new XStreamPersistenceFactory(load, files) ;
		}
	}

	@Override
	protected void setUp() throws Exception
	{
		super.setUp() ;
		this.clearDatabase() ;
		this.persistenceGenerator = this.newPersistenceGenerator(PersistenceController.LOAD, false) ;
	}

}
